import { Card, Form, Select } from 'antd';

import { ApiBody } from '@/api';
import { NODE_TYPE } from '@/constants/config';
import { useCurrentNode } from '@/hooks/useCurrentNode';

import { Rules } from '../../Rules';
import { useDataSource } from '../DataLoad/data';
import { Mapping } from './mapping';

export const DataModifyConfig = memo(() => {
  const [form] = Form.useForm<ApiBody<'post', '/ds/execute'>>();
  const { getNodeDataFor, setNodeDataFor, variable2Options } = useCurrentNode<NODE_TYPE.DATA_MODIFY>();
  const { dataSetOptions, colsVariables, rightVariables, getColsOptions } = useDataSource();
  const data = getNodeDataFor();
  const showMapping = !!data?.dataSource;

  const leftOptions = useMemo(() => {
    return variable2Options(rightVariables);
  }, [rightVariables, variable2Options]);

  const rightOptions = useMemo(() => {
    return variable2Options(colsVariables);
  }, [colsVariables, variable2Options]);

  useEffect(() => {
    form.setFieldsValue(data!);
  }, [data, form, getNodeDataFor]);

  return (
    <Card size="small" title="数据更新设置" className="data-modify-config mt-12">
      <Form
        form={form}
        onValuesChange={(_, value) => {
          setNodeDataFor({
            ...data,
            ...value
          });
          getColsOptions();
        }}
        layout="vertical">
        <Form.Item name="dataSource" required label="数据集">
          <Select
            allowClear
            showSearch
            placeholder="请选择数据集"
            onChange={(val) => {
              const info = dataSetOptions?.find((item) => item.value === val);
              if (!info) return;
              setNodeDataFor({
                ...data,
                dataSource: val,
                tableName: info?.tableName
              });
            }}
            options={dataSetOptions}
          />
        </Form.Item>
        <Form.Item required name="criteria" label="条件">
          <Rules leftVariables={colsVariables} rightVariables={rightVariables} />
        </Form.Item>

        {showMapping && (
          <Form.Item name="mapping" label="字段映射">
            <Mapping leftOptions={leftOptions} rightOptions={rightOptions} />
          </Form.Item>
        )}
      </Form>
    </Card>
  );
});
